<template>
  <span>
    <span>
      <!--<el-select v-model="value" placeholder="请选择拓扑图" size="small" style="margin-right:8px;">
              <el-option v-for="item in topoBaseInfo" :key="item.sysmapid" :label="item.name" :value="item.sysmapid">
              </el-option>
          </el-select>-->
      <div class="btn-group">
        <!-- <el-input v-model="input" :placeholder="$t('Search Resource Tree')" size='small' icon="search" @change="handleSelect" style="width:150px"></el-input> -->
        <el-autocomplete class="inline-input" v-model="input" :fetch-suggestions="querySearch" :placeholder="$t('Search Resource Tree')" size='small' icon="search" @select="handleSelect" style="width:150px"></el-autocomplete>
        <scriptComp class="script-comp"></scriptComp>
      </div>
    </span>
    <!-- 弹出对话框  -->
    <!-- <div id="bus-topo-dialog" style="display:none">
      <component :is="currentViewComp" transition="fade" transition-mode="out-in" keep-alive @transferNewSysmap="transferNewSysmap" @transferCloseDialog="transferCloseDialog" @transferCheckedNodes="transferCheckedNodes" :busType="busType"></component>
    </div> -->
  </span>
</template>
<script>
import Vue from 'vue'
import topoApi from 'api/topo'
import iconApi from 'api/config/iconmanager'
import eventHubs from 'common/eventHubs'
import addTopoEle from 'common/topo/addTopoElement'
import art from 'utils/artdialog'
import busTopoAddComp from 'views/topo/topoCreate.vue'
import { CreateEdgeInteractor } from 'common/topo/CreateEdgeInteractor.js'
import deviceTreeComp from 'views/device/deviceTree.vue'
import scriptComp from 'components/script/index.vue'

import btnEvent from 'common/topo/btnEvent'

import { createNode } from 'common/topo/addTopoElement.js'
export default {
  data() {
    return {
      busType: '1',
      value: '',
      input: '',
      graphView: null,
      treeView: null,
      topoBaseInfo: [],
      currentViewComp: null,
      bustopoDialog: null,
      importDeviceDialog: null,
      imageAndHostidMap: {},
      currentNodeOrLink: null,
      currentMapElementData: null,
      topoIconData: {},
      resourceTreeData: []
    }
  },
  mounted() {
    const sysmapidTmp = this.$route.query.sysmapid;
    if (sysmapidTmp != undefined && sysmapidTmp != null) {
      this.value = sysmapidTmp;
    }
    this.addEventListener();
    this.initTopoData();
    this.initImageAndHostidMap();
  },
  methods: {
    initImageAndHostidMap() {
      const self = this;
      iconApi.getImageAndHostid().then(response => {
        self.imageAndHostidMap = response.data;
      });
    },
    addEventListener() {
      const self = this;
      // 事件处理
      eventHubs.getEventHub().$on('topoGraphView', (topoGraphView) => { //Hub接收事件
        self.graphView = topoGraphView;
        // self.mouseupEvent();
      });
      eventHubs.getEventHub().$on('topoTreeView', (topoTreeView) => {
        self.treeView = topoTreeView;
      });
      eventHubs.getEventHub().$on('sysmapidChange', (sysmapid) => { //Hub接收事件
        self.value = sysmapid;
      });
      // // 工具栏按钮事件
      // // 新增拓扑图
      // $('#topo-toolbar').on('click', '#bus-topo-add', function() {
      //     console.log('新增拓扑图')
      //   self.currentViewComp = busTopoAddComp;
      //   self.bustopoDialog = art.artdialog(self.$t('New Business'), $('#bus-topo-dialog'), 300, 150, 'bustopodialog');
      // });
      // // 删除拓扑图
      // $('#topo-toolbar').on('click', '#bus-topo-delete', function() {
      //     console.log('删除拓扑图')
      //   self.$confirm(self.$t('Are you sure delete?', [self.value]), self.$t('Prompt'), {
      //     type: 'warning'
      //   }).then(() => {
      //     topoApi.deleteSysmap(self.value).then(response => {
      //       self.$message({
      //         type: 'success',
      //         message: self.$t('Deleted Successfully')
      //       });
      //     }).catch(error => {
      //       self.$message({
      //         type: 'error',
      //         message: self.$t('Failed to delete')
      //       });
      //     });
      //   }).catch(() => {
      //     self.$message({
      //       type: 'info',
      //       message: self.$t('Cancel to delete')
      //     });
      //   });
      // });

      // // 导入设备
      // $('#topo-toolbar').on('click', '#bus-topo-import-device', function() {
      //     console.log('导入设备')
      //   self.currentViewComp = deviceTreeComp;
      //   self.importDeviceDialog = art.artdialog(self.$t('Import Device'), $('#bus-topo-dialog'), 400, 500, 'importdevicedialog');
      // });

      // // 新增连接
      // $('#topo-toolbar').on('click', '#bus-topo-add-link', function() {
      //     console.log('新增连接')
      //   const message = { success: self.$t('Created Successfully'), failed: self.$t('Failed to create') };
      //   btnEvent.topoAddLink(self.graphView, self.value, message);
      // });

      // // 删除拓扑图元素
      // $('#topo-toolbar').on('click', '#topo-delete-map-element', function() {
      //     console.log('删除拓扑图元素')
      //     const message = { success: self.$t('Deleted Successfully'), failed: self.$t('Failed to delete'), info: self.$t('Cancel to delete') };
      //     btnEvent.deleteMapElement(self.graphView, message);
      // });
    },
    initSearchData() {
      const self = this;
      if (self.treeView != null && self.treeView != undefined) {
        let datas = []
        self.treeView.getDataModel().each(function(item,index){
          if(item instanceof ht.Node){
            let data = {value:item.getName(),id:item}
            datas.push(data)
            console.log(data)
          }
        })
        datas.sort(function(a,b){
          return a.value.localeCompare(b.value)
        })
        self.resourceTreeData = datas?datas:[]
      }
    },
    querySearch(queryString,callback){
      const self = this
      if(self.resourceTreeData.length == 0){
        self.initSearchData()
      }
      var restaurants = self.resourceTreeData;
      var results = queryString ? restaurants.filter(self.createFilter(queryString)) : restaurants;
        // 调用 callback 返回建议列表的数据
      if(!results){
        results = []
      }
      callback(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.indexOf(queryString.toLowerCase()) === 0);
      };
    },
    handleSelect(item) {
      const self = this;
      console.log(self)
      if (self.graphView != null && self.graphView != undefined) {
        if (item) {
          self.graphView.getDataModel().getSelectionModel().setSelection(item.id)
        } else {
          self.graphView.getDataModel().getSelectionModel().removeSelection(item.id)
        }
      }
    },
    initTopoData() {
      const self = this;
      topoApi.querySysmapBaseInfoByType(1).then(response => {
        self.topoBaseInfo = response.data;
      }).catch(err => {
        self.$message({ type: 'error', message: self.$t('get topo data faile') + ', err=' + err });
      });
    },
    createTopoGraph(topoId) {
      // 情况dataModel
      const dataModel = this.graphView.getDataModel();
      dataModel.clear();
      const self = this;

      this.$store.dispatch('getMapDataById', topoId).then((response) => {
        self.currentMapData = response.data[0];
        addTopoEle.setTopoStyle(response.data[0], self.graphView, self.topoIconData);
        self.layout();
      }).catch(err => {
        console.log(err)
        self.$message({ type: 'error', message: self.$t('get topo data failed') + ', ' + err });
      });
    },
    layout() {
      const self = this;
      // 布局设置
      const autoLayout = new ht.layout.AutoLayout(this.graphView);
      // this.autoLayout.setAnimate(animate);
      autoLayout.layout('symmetric', function() {
        self.graphView.fitContent(true);
      });
    },
    initTopoIconData(topoId) {
      const self = this;
      iconApi.syncQueryTopoIconData(topoId, function(data) {
        self.topoIconData = data;
      });
    },
    transferNewSysmap(newSysmap) {
      if (newSysmap != null && newSysmap != undefined) {
        this.topoBaseInfo.push(newSysmap);
      }
      if (this.bustopoDialog != null) {
        this.bustopoDialog.close();
      }
      this.$message(this.$t("Created Successfully"));
    },
    closeDialog() {
      if (this.bustopoDialog != null) {
        this.bustopoDialog.close();
      }
      if (this.importDeviceDialog != null) {
        this.importDeviceDialog.close();
      }
    },
    transferCloseDialog(msg) {
      this.closeDialog();
      this.$message(msg);
    },
    transferCheckedNodes(checkedNodes) {
      const self = this;
      let selements = [];
      const sysmapid = this.$store.state.topo.sysmapid;
      const dataModel = this.graphView.getDataModel();

      // api添加记录
      $.each(checkedNodes, function() {
        const etype = this.type;
        if (etype == 2) {
          let element = {};
          element.label = this.host;
          element.elementid = this.id;
          element.sysmapid = sysmapid;
          element.elementtype = "0";
          const sysimage = self.imageAndHostidMap[this.hostid];
          if (!self.isObjBlank(sysimage)) {
            element.iconid_off = sysimage.imageid;
          } else {
            element.iconid_off = "150";
          }
          element.x = 200;
          element.y = 200;
          selements.push(element);
        }
      });
      //使用过滤函数过滤数组元素 过滤函数必须返回 true 以保留元素或 false 以删除元素。
      let result = $.grep(selements, function(ele){
          let flag = true
          dataModel.each(function(node,index){
            let data = node.getAttr('data')
            if(ele.elementid == data.elementid){
              flag = false
              return
            }
          })
          return flag
      });
      if(result.length == 0){
          self.$message('拓扑图中已存在选中元素！');
          self.closeDialog();
          return
      }
      topoApi.createMapElement(result).then(response => {
        if (response.status == 200) {
          const elementData = response.data;
          $.each(elementData, function() {
            // 创建图形元素
            var newNode = createNode(this, self.sysIcons,self.defaultNodeImg)
            dataModel.add(newNode);
          });
          self.layout(); // 重新自动布局
          self.closeDialog();
          self.$message(self.$t('Created Successfully'));
        }
      }).catch(err => {
        self.$message.error(self.$t('Failed to create'));
      });
    },
    isObjBlank(obj) {
      return (obj === null) || (obj === undefined) || (obj === '');
    }
  },
  components: {
    busTopoAddComp, deviceTreeComp, scriptComp
  },
  computed: {
    sysIcons() {
      return this.$store.state.topo.sysIcons;
    },
    defaultNodeImg(){
      return this.$store.state.topo.defaultNodeImg;
    }
  },
  watch: {
    value: function(newValue, oldValue) {
      if (newValue != oldValue) {
        this.$store.dispatch('setCurSysmapid', newValue);
        this.initTopoIconData(newValue);
        this.createTopoGraph(newValue);
      }
    }
  }
}
</script>
